package com.usian.common.exception;

import com.usian.common.dtos.ResponseResult;
import com.usian.common.enums.AppHttpCodeEnum;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *  通用异常处理类
 */
@ControllerAdvice
@Slf4j
public class ExceptionCatch {

    /**
     * 异常处理方案
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseResult handleRuntimeException(RuntimeException e){
        log.error(e.getMessage());
        return ResponseResult.error(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 自定义异常处理方案
     */
    @ExceptionHandler(LeadException.class)
    @ResponseBody
    public ResponseResult handleLeadException(LeadException e){
        log.error(e.getMessage());
        if(StringUtils.isNotBlank(e.getMessage())){
            return ResponseResult.error(e.getEnums(),e.getMessage());
        }else{
            return ResponseResult.error(e.getEnums());
        }
    }

    /**
     * 参数异常处理方案
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseResult handleMethodArgException(MethodArgumentNotValidException e){
        log.error(e.getMessage());
        return ResponseResult.error(AppHttpCodeEnum.PARAM_INVALID,e.getBindingResult().getFieldError().getDefaultMessage());
    }

}
